<template>
  <div class="inventory-report">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.productCode" placeholder="请输入商品编码" clearable />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 100px">
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库存状态">
            <el-select v-model="searchForm.stockStatus" placeholder="请选择库存状态" clearable style="width: 100px">
              <el-option label="正常" value="NORMAL" />
              <el-option label="低库存" value="LOW" />
              <el-option label="无库存" value="EMPTY" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计卡片 -->
      <div class="stat-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">商品总数</div>
              </template>
              <div class="stat-value">{{ statistics.productCount }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">库存总数量</div>
              </template>
              <div class="stat-value">{{ statistics.totalQuantity }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">库存总金额</div>
              </template>
              <div class="stat-value">¥{{ formatAmount(statistics.totalAmount) }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card warning">
              <template #header>
                <div class="stat-header">低库存商品</div>
              </template>
              <div class="stat-value">{{ statistics.lowStockCount }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="chart-area">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-title">库存金额分布</div>
              </template>
              <div class="chart-container" ref="amountChartContainer"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-title">库存状态分布</div>
              </template>
              <div class="chart-container" ref="statusChartContainer"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 明细表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" width="200" />
        <el-table-column prop="specifications" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="warehouseName" label="仓库" width="120" >
          <template #default="scope"> 
            {{ getWarehouseName(scope.row.warehouseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存数量" width="100" align="right" />
        <el-table-column label="进价"  align="right">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.purchasePrice) }}
          </template>
        </el-table-column>

        <el-table-column label="库存状态">
          <template #default="scope">
            <el-tag :type="getStockStatusTag(scope.row)">
              {{ getStockStatusLabel(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
      
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { warehouseApi, inventoryApi } from '../../api'
// import * as XLSX from 'xlsx'

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const { data } = await warehouseApi.getList()
    warehouseList.value = data.records.filter(item => item.status === 1) || []
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  }
}

// 仓库列表
const warehouseList = ref([])

// 获取仓库名称
const getWarehouseName = (warehouseId) => {
  const warehouse = warehouseList.value.find(item => item.id === warehouseId)
  return warehouse ? warehouse.warehouseName : '-'
}

// 搜索表单
const searchForm = reactive({
  productCode: '',
  productName: '',
  warehouseId: '',
  stockStatus: ''
})

// 统计数据
const statistics = reactive({
  productCount: 0,
  totalQuantity: 0,
  totalAmount: 0,
  lowStockCount: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 图表实例
let amountChart = null
let statusChart = null

// 添加本地数据存储
const allData = ref([])
const filteredData = ref([])

// 修改统计数据的计算逻辑
const calculateStatistics = (inventoryList) => {
  statistics.productCount = inventoryList.length
  statistics.totalQuantity = inventoryList.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0)
  statistics.totalAmount = inventoryList.reduce((sum, item) => {
    return sum + (Number(item.quantity) || 0) * (Number(item.purchasePrice) || 0)
  }, 0)
  statistics.lowStockCount = inventoryList.filter(item => Number(item.quantity) <= 10).length
}

// 修改获取报表数据的方法
const getReportData = async () => {
  loading.value = true
  try {
    // 获取所有数据
    const { data } = await inventoryApi.getListAll()
    console.log('data', data)
    allData.value = data.map(item => ({
      ...item,
      amount: (Number(item.quantity) || 0) * (Number(item.purchasePrice) || 0)
    }))
    console.log('allData', allData.value)
    // 执行搜索过滤
    handleFilter()
    console.log('filteredData', filteredData.value)
    // 更新统计和图表
    calculateStatistics(filteredData.value)
    updateCharts(filteredData.value)
    
    // 更新分页数据
    updatePageData()
    
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 添加搜索过滤方法
const handleFilter = () => {
  filteredData.value = allData.value.filter(item => {
    console.log('item', item)
    const matchProductCode = !searchForm.productCode || 
      item.productCode.toLowerCase().includes(searchForm.productCode.toLowerCase())
    console.log('matchProductCode', matchProductCode)
    const matchProductName = !searchForm.productName || 
      item.productName.toLowerCase().includes(searchForm.productName.toLowerCase())
    console.log('matchProductName', matchProductName)
    
    const matchWarehouse = !searchForm.warehouseId || 
      item.warehouseId === searchForm.warehouseId
    console.log('matchWarehouse', matchWarehouse)
    const matchStatus = !searchForm.stockStatus || 
      getStockStatus(item) === searchForm.stockStatus
    console.log('matchStatus', matchStatus)
    return matchProductCode && matchProductName && matchWarehouse && matchStatus
  })
  console.log('filteredData', filteredData.value)
  // 更新总数
  total.value = filteredData.value.length
  
  // 重置到第一页
  currentPage.value = 1
  //更新图表
  updateCharts(filteredData.value)
  // 更新页面数据
  updatePageData()
}

// 添加更新分页数据的方法
const updatePageData = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  tableData.value = filteredData.value.slice(startIndex, endIndex)
}

// 修改搜索处理
const handleSearch = () => {
  handleFilter()
}

// 修改分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  updatePageData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  updatePageData()
}

// 修改导出方法
const handleExport = async () => {
  try {
    // 使用过滤后的数据导出
    const exportData = filteredData.value.map(item => ({
      商品编码: item.product_code,
      商品名称: item.product_name,
      规格: item.specifications,
      单位: item.unit,
      仓库: item.warehouse_name,
      库存数量: item.quantity,
      采购单价: item.purchase_price,
      销售单价: item.selling_price,
      库存状态: getStockStatusLabel(item)
    }))
    
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '库存报表')
    
    // 导出文件
    XLSX.writeFile(workbook, `库存报表_${new Date().toLocaleDateString()}.xlsx`)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 更新图表
const updateCharts = (inventoryList) => {
  if (!amountChart || !statusChart) return

  // 库存金额分布图（按仓库）
  const warehouseData = []
  const warehouseMap = new Map()
  
  inventoryList.forEach(item => {
    const amount = warehouseMap.get(item.warehouseId) || 0
    warehouseMap.set(item.warehouseId, amount + Number(item.amount || 0))
  })
  
  warehouseMap.forEach((amount, warehouseId) => {
    warehouseData.push({
      name: getWarehouseName(warehouseId),
      value: amount
    })
  })

  amountChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: warehouseData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 库存状态分布图
  const statusData = [
    { name: '正常', value: 0 },
    { name: '低库存', value: 0 },
    { name: '无库存', value: 0 }
  ]

  inventoryList.forEach(item => {
    const status = getStockStatus(item)
    switch(status) {
      case 'NORMAL':
        statusData[0].value++
        break
      case 'LOW':
        statusData[1].value++
        break
      case 'EMPTY':
        statusData[2].value++
        break
    }
  })

  statusChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: statusData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

// 初始化图表
const initCharts = () => {
  if (amountChartContainer.value && statusChartContainer.value) {
    amountChart?.dispose()
    statusChart?.dispose()
    
    amountChart = echarts.init(amountChartContainer.value)
    statusChart = echarts.init(statusChartContainer.value)
    
    getReportData()
  }
}

// 监听窗口大小变化
const handleResize = () => {
  amountChart?.resize()
  statusChart?.resize()
}

// 获取库存状态
const getStockStatus = (row) => {
  const quantity = Number(row.quantity || 0)
  if (quantity <= 0) return 'EMPTY'
  if (quantity <= 10) return 'LOW'
  return 'NORMAL'
}

// 获取库存状态标签类型
const getStockStatusTag = (row) => {
  const status = getStockStatus(row)
  const types = {
    'NORMAL': 'success',
    'LOW': 'warning',
    'EMPTY': 'danger'
  }
  return types[status]
}

// 获取库存状态显示文本
const getStockStatusLabel = (row) => {
  const status = getStockStatus(row)
  const labels = {
    'NORMAL': '正常',
    'LOW': '低库存',
    'EMPTY': '无库存'
  }
  return labels[status]
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null || isNaN(amount)) {
    return '0.00'
  }
  return Number(amount).toFixed(2)
}

// 重置搜索
const resetSearch = () => {
  searchForm.productCode = ''
  searchForm.productName = ''
  searchForm.warehouseId = ''
  searchForm.stockStatus = ''
  handleSearch()
}

// 图表容器引用
const amountChartContainer = ref(null)
const statusChartContainer = ref(null)

// 日期格式化函数
const formatDate = (date) => {
  if (!date) return '---'  // 如果没有日期，返回'-'
  // 如果日期包含时间，只保留日期部分
  if (date.includes(' ')) {
    return date.split(' ')[0]
  }
  return date
}

// 组件挂载时
onMounted(async () => {
  await getWarehouseList()  // 先获取仓库列表
  initCharts()  // 然后初始化图表
  window.addEventListener('resize', handleResize)
})

// 组件卸载时
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  amountChart?.dispose()
  statusChart?.dispose()
})
</script>

<style scoped>
.inventory-report {
  height: 100%;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
  min-width: 1200px;
}

.el-card {
  height: 100%;
  overflow-y: auto;
}

.search-area {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-header {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-top: 10px;
}

.chart-area {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 